define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'goods/index',
        add_url: 'goods/add',
        edit_url: 'goods/edit',
        delete_url: 'goods/delete',
        export_url: 'goods/export',
        modify_url: 'goods/modify',
        images_url: 'goods.banner/index'
    };
    var a = 0;
    var upload = layui.upload;
    var form = layui.form;
    var Controller = {

        index: function () {
            ea.table.render({
                init: init,
                toolbar: ['refresh', 'add', 'delete'],
                cols: [[
                    {type: 'checkbox'},
                    {field: 'id', title: 'ID', search: false},
                    {field: 'price_low', title: '价格最小值', hide: true},
                    {field: 'price_high', title: '价格最大值', hide: true},
                    {field: 'shop_name', title: '店铺名'},
                    {field: 'category_name', title: '分类', fieldAlias: 'gc.name'},
                    {field: 'name', title: '商品名称', fieldAlias: 'g.name'},
                    {field: 'show_price', title: '展示价格', search: false},

                    {
                        field: 'status',
                        title: '状态',
                        templet: ea.table.switch,
                        selectList: {0: '禁用', 1: '启用'},
                        fieldAlias: 'g.status'
                    },

                    /*{field: 'sku_json', title: '规格选项'},*/
                    {
                        field: 'sort', title: '排序值', edit: 'text', search: false, sort: function () {
                            console.log(111)
                        }
                    },
                    {field: 'img', title: '商品主图', imageHeight: 80, templet: ea.table.image, search: false},
                    {field: 'sales', title: '销量', search: false, edit: 'text'},
                    {
                        field: 'stock', title: '库存', search: false, templet: function (k, v) {
                            return '<span class="search_stock" id=' + k.id + '>' + k.total_stock + '</span>';
                        }
                    },
                    {field: 'is_sale', title: '在售状态', templet: ea.table.switch, selectList: {0: '下架', 1: '上架'}},
                    // {field: 'create_time', title: '添加时间',search: 'range'},
                    {
                        width: 250, title: '操作', templet: ea.table.tool,
                        operat: [
                            'edit',
                            [{
                                text: '图集',
                                url: init.images_url,
                                method: 'open',
                                fieldExtra: {'goods_id': 'id'},
                                auth: 'images',
                                class: 'layui-btn layui-btn-xs layui-btn-normal',
                                extend: 'data-full="true"',
                            }],
                            'delete']
                    },
                ]],
                done: function () {
                    $(".layui-table-body>table>tbody>tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                    });

                    /**
                     * 模拟用户点击操作
                     */

                    if(a == 0){
                        $(".layui-icon-search").click()
                        a = 1;
                    }


                    $(".search_stock").click(function () {
                        var id = $(this).attr('id')

                        // layer.open(
                        //     {
                        //         type:1,
                        //         content:'<table class="layui-table" lay-size="sm">小尺寸表格</table>',
                        //     }
                        //     // res.data.map(function (item, index) {
                        //     //
                        //     // })
                        // )

                        $.ajax({
                            url: 'stockList',
                            type: 'get',
                            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                            dataType: "json",
                            headers:"{'X-CSRF-TOKEN': window.CONFIG.CSRF_TOKEN}",
                            data: {id:id},
                            timeout: 3000,
                            success: function (res) {
                                var html='<table class="layui-table">'
                                    +'<colgroup>'
                                    +'<col width="250">'
                                    +'<col width="100">'
                                    +'</colgroup>'
                                    +'<thead>'
                                    +'<tr>'
                                    +'<th>规格名称</th>'
                                    +'<th>库存</th>'
                                    +'</tr> '
                                    +'</thead>'
                                    +'<tbody>';
                                res.data.map(function (item, index) {
                                    html += '<tr>'
                                    +'<td>'+item.sku_json[0].name+':'+item.sku_json[0].value+'</td>'
                                    +'<td>'+item.stock+'</td>'
                                    +'</tr>'
                                })
                                html +='</table>'
                                layer.open(
                                    {
                                        type:1,
                                        content:html,
                                    }
                                )
                            },
                            error: function (xhr, textstatus, thrown) {

                            },
                            complete: function(){
                                // @todo 刷新csrf-token
                            }
                        });
                    })
                },
            });

            ea.listen();
        },
        add: function () {
            ea.listen();
            var specAll = [];
            var skuJsonArr = [];

            /* specAll = [
                 {
                     name:'颜色',
                     value:[
                         '红色',
                         '绿色'
                     ]
                 }
             ];*/
            function remove(i) {
                specAll.splice(i, 1)
                buildSpec();
            }

            function remove1(i, ii) {
                specAll[i].value.splice(ii, 1)
                buildSpec();
            }

            $(document).on('click', '.remove', function () {
                if ($(this).hasClass('all')) {
                    remove($(this).attr('data-index'))
                } else {
                    remove1($(this).attr('data-index'), $(this).attr('data-index1'))
                }
                console.log(specAll);
            });

            function discarts() {
                //笛卡尔积
                var twodDscartes = function (a, b) {
                    var ret = [];
                    for (var i = 0; i < a.length; i++) {
                        for (var j = 0; j < b.length; j++) {
                            ret.push(ft(a[i], b[j]));
                        }
                    }
                    return ret;
                }
                var ft = function (a, b) {
                    if (!(a instanceof Array))
                        a = [a];
                    var ret = a.slice(0);
                    ret.push(b);
                    return ret;
                }
                //多个一起做笛卡尔积
                return (function (data) {
                    var len = data.length;
                    if (len == 0)
                        return [];
                    else if (len == 1)
                        return data[0];
                    else {
                        var r = data[0];
                        for (var i = 1; i < len; i++) {
                            r = twodDscartes(r, data[i]);
                        }
                        return r;
                    }
                })(arguments.length > 1 ? arguments : arguments[0]);
            }

            function uploadBind() {
                $.each($('.skuUpload'), function (i, v) {
                    console.log(i);
                    var
                        uploadName = $(this).attr('data-upload'),
                        uploadNumber = $(this).attr('data-upload-number') || 'one',
                        uploadSign = $(this).attr('data-upload-sign') || '|',
                        uploadAccept = $(this).attr('data-upload-accept') || 'file',
                        uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
                        elem = "input[name='" + uploadName + "']",
                        uploadElem = this;

                    // 监听上传事件
                    upload.render({
                        elem: this,
                        url: '/' + CONFIG.ADMIN + '/ajax/upload',
                        exts: 'gif|ico|icon|jpg|png',
                        accept: uploadAccept,//指定允许上传时校验的文件类型
                        acceptMime: uploadAcceptMime,//规定打开文件选择框时，筛选出的文件类型
                        multiple: false,//是否多文件上传
                        //headers:admin.headers(),
                        before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                            layer.load(); //上传loading
                        },
                        done: function (res) {
                            layer.closeAll('loading'); //关闭loading
                            if (res.code === 1) {
                                var url = res.data.url;
                                if (uploadNumber !== 'one') {
                                    var oldUrl = $(elem).val();
                                    if (oldUrl !== '') {
                                        url = oldUrl + uploadSign + url;
                                    }
                                }
                                $(uploadElem).html('<img src="' + url + '" width="28" height="28">');
                                $(uploadElem).siblings('.imgInput').val(url);
                                //$(elem).val(url);
                                // $(elem).trigger("input");
                                // admin.msg.success(res.msg);
                            } else {
                                // admin.msg.error(res.msg);
                            }
                            return false;
                        },
                        error: function (index, upload) {
                            layer.closeAll('loading'); //关闭loading
                        }
                    });

                    // 监听上传input值变化
                    $(elem).bind("input propertychange", function (event) {
                        var urlString = $(this).val(),
                            urlArray = urlString.split(uploadSign),
                            uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";

                        $('#bing-' + uploadName).remove();
                        if (urlString.length > 0) {
                            var parant = $(this).parent('div');
                            var liHtml = '';
                            $.each(urlArray, function (i, v) {
                                liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                            });
                            parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                        }

                    });

                    // 非空初始化图片显示
                    if ($(elem).val() !== '') {
                        $(elem).trigger("input");
                    }
                });
            }

            function buildSpec() {
                // $('.panel-default').remove();
                //  $('#specTable').html('');
                var thHtml = '';
                var tdArr = [];
                var discartArr = [];
                var single = true;
                var html = '';
                specAll.forEach(function (d, i) {
                    html += '\n' +
                        '                    <header class="panel-heading" style="background: #ddd">\n' +
                        '                        <b>' + d.name + '</b> <span title="移除" class="remove all" data-index="' + i + '">×</span>\n' +
                        '                    </header>\n' +
                        '                    <div class="row">\n' +
                        '                        <div class="l">\n' +
                        '                            <div class="input-group" >\n' +
                        '                                <input type="text" placeholder="多规格以空格隔开" id="specName' + i + '" class="form-control layui-input specName">\n' +
                        '                                <span class="input-group-addon pointer"><i class="fa fa-plus addChild"></i></span>\n' +
                        '                            </div>\n' +
                        '                        </div>\n' +
                        '                        <div class="r">\n';
                    if (d.value.length > 0) {
                        if (i == 0) {
                            // var len = d.child.length;
                            // var lenT = Math.pow(len,specAll.length);
                            discartArr = d.value
                        } else {
                            discartArr = discarts(discartArr, d.value);
                            single = false;
                        }

                        d.value.forEach(function (d, ii) {
                            html += '<div class="wanl-specs-tag">' + d + '<span title="移除" class="remove"  data-index="' + i + '"  data-index1="' + ii + '">×</span></div>';
                            // console.log(tdArr[ii]);
                            /* if(typeof tdArr[ii] == 'undefined'){
                                 tdArr[ii] = [];
                             }*/
                            /*for(var n=0;n<len;n++){
                                if(typeof tdArr[n] == 'undefined'){
                                    tdArr[n] = [];
                                }
                                if(i==0){
                                    tdArr[n].push(d);
                                }
                            }*/
                            // tdArr[ii].push(d);
                        })
                        thHtml += '<th width="80"> ' + d.name + '</th>';
                    }

                    html += '                        </div>\n' +
                        '                    </div>\n' +
                        '                ';
                })

                $('#specDetail').html(html);
                if (single == true) {
                    // discartArr = [discartArr]
                }
                console.log(single, discartArr);
                if (thHtml != '') {
                    var tableHtml = '\n' +
                        '                    <table class="table table-bordered">\n' +
                        '                        <thead>\n' +
                        '                        <tr class="info text-info">\n' + thHtml +
                        '                            <th width="40">图片</th>\n' +
                        '                            <th width="80">原价</th>\n' +
                        '                            <th width="80">现价</th>\n' +
                        '                            <th width="80">库存</th>\n' +
                        //  '                            <th width="80">重量(k)</th>\n' +
                        '                            <th width="80">编码</th>\n' +
                        '                        </tr>\n' +
                        '                        </thead>\n' +
                        '                        <tbody>\n';
                    for (var a = 0; a < discartArr.length; a++) {
                        var tdHtml = '';
                        if (single == true) {
                            tdHtml += '<td>' + discartArr[a] + '</td>';
                        } else {
                            for (var name in discartArr[a]) {
                                tdHtml += '<td>' + discartArr[a][name] + '</td>';
                            }
                        }

                        tableHtml += '<tr>\n' + tdHtml +
                            '                            <td><!---->  <label\n' +
                            '                                    for="skuImg0" class="wanl_sku_img"><input type="hidden" name="specs[img][]" class="imgInput" style="display: none;">\n' +
                            '                                <div class="skuUpload"><i class="fa fa-picture-o"></i></div>\n' +
                            '                            </label></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[original_price][]"\n' +
                            '                                       class="input-sm form-control wanl-market_price layui-input"></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[price][]"\n' +
                            '                                       class="input-sm form-control wanl-price layui-input"></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[stock][]"\n' +
                            '                                       class="input-sm form-control wanl-stock layui-input"></td>\n' +
                            //'                            <td><input type="number" name="row[weigh][]" class="input-sm form-control wanl-weigh layui-input"></td>\n' +
                            '                            <td><input type="text" name="specs[sku_code][]" class="input-sm form-control wanl-sn layui-input"></td>\n' +
                            '                        </tr>';
                    }

                    tableHtml += '\n' +
                        '                        </tbody>\n' +
                        '                    </table>\n' +
                        '                    <div><span>\n' +
                        //'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t是否要批量设置？\n' +
                        '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t</span></div>\n' +
                        '                ';
                }
                $("[name='specs_all']").val(JSON.stringify(specAll));
                $('#specTable').html(tableHtml);
                uploadBind();
            }

            $(document).on('click', '#addspec', function () {
                var skuJson = $.trim($('#skuJson').val());
                if (skuJson == '') {
                    ea.msg.error('请填写规格');
                    return false;
                }
                skuJsonArr = skuJson.split(' ').filter(function (d) {
                    return d;
                    //console.log(d)
                });

                skuJsonArr.forEach(function (d, i) {
                    specAll.push({
                        name: d,
                        value: []
                    })
                })
                $('#skuJson').val('');
                buildSpec();
                console.log(specAll);
            });
            $(document).on('click', '.addChild', function (d) {
                var index = $('.addChild').index($(this));
                var skuJson = $.trim($('#specName' + index).val());
                if (skuJson == '') {
                    ea.msg.error('请填写规格');
                    return false;
                }
                var skuJsonArr = skuJson.split(' ').filter(function (d) {
                    return d;
                });
                skuJsonArr.forEach(function (d, i) {
                    specAll[index].value.push(d);
                })

                $('#specName' + index).val('');
                buildSpec();
                /* skuJsonArr.forEach(function(d,i){
                     var html = '<div class="wanl-specs-tag">红色<span title="移除" class="remove">×</span></div>';
                     $('#specContainer').append(html);
                 })*/
                console.log(specAll);
            })

            form.on('radio(spec_type)', function (data) {
                if (data.value == 0) {
                    $('#specContainer0').show();
                    $('#specContainer1').hide();
                    uploadBind();
                } else {
                    $('#specContainer1').show();
                    $('#specContainer0').hide();
                }
                console.log(data.value);
            });
            uploadBind();
        },
        edit: function () {
            ea.listen();
            var specAll = specAll1 || [];
            var skuJsonArr = [];

            function remove(i) {
                specAll.splice(i, 1)
                buildSpec();
            }

            function remove1(i, ii) {
                specAll[i].value.splice(ii, 1)
                buildSpec();
            }

            $(document).on('click', '.remove', function () {
                if ($(this).hasClass('all')) {
                    remove($(this).attr('data-index'))
                } else {
                    remove1($(this).attr('data-index'), $(this).attr('data-index1'))
                }
                console.log(specAll);
            });

            function discarts() {
                //笛卡尔积
                var twodDscartes = function (a, b) {
                    var ret = [];
                    for (var i = 0; i < a.length; i++) {
                        for (var j = 0; j < b.length; j++) {
                            ret.push(ft(a[i], b[j]));
                        }
                    }
                    return ret;
                }
                var ft = function (a, b) {
                    if (!(a instanceof Array))
                        a = [a];
                    var ret = a.slice(0);
                    ret.push(b);
                    return ret;
                }
                //多个一起做笛卡尔积
                return (function (data) {
                    var len = data.length;
                    if (len == 0)
                        return [];
                    else if (len == 1)
                        return data[0];
                    else {
                        var r = data[0];
                        for (var i = 1; i < len; i++) {
                            r = twodDscartes(r, data[i]);
                        }
                        return r;
                    }
                })(arguments.length > 1 ? arguments : arguments[0]);
            }

            function uploadBind() {
                $.each($('.skuUpload'), function (i, v) {
                    var
                        uploadName = $(this).attr('data-upload'),
                        uploadNumber = $(this).attr('data-upload-number') || 'one',
                        uploadSign = $(this).attr('data-upload-sign') || '|',
                        uploadAccept = $(this).attr('data-upload-accept') || 'file',
                        uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
                        elem = "input[name='" + uploadName + "']",
                        uploadElem = this;

                    // 监听上传事件
                    upload.render({
                        elem: this,
                        url: '/' + CONFIG.ADMIN + '/ajax/upload',
                        exts: 'gif|ico|icon|jpg|png',
                        accept: uploadAccept,//指定允许上传时校验的文件类型
                        acceptMime: uploadAcceptMime,//规定打开文件选择框时，筛选出的文件类型
                        multiple: false,//是否多文件上传
                        //headers:admin.headers(),
                        before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                            layer.load(); //上传loading
                        },
                        done: function (res) {
                            layer.closeAll('loading'); //关闭loading
                            if (res.code === 1) {
                                var url = res.data.url;
                                $(uploadElem).html('<img src="' + url + '" width="28" height="28">');
                                $(uploadElem).siblings('.imgInput').val(url);
                            } else {
                                // admin.msg.error(res.msg);
                            }
                            return false;
                        },
                        error: function (index, upload) {
                            layer.closeAll('loading'); //关闭loading
                        }
                    });
                });
            }

            function buildSpec(specs) {
                var thHtml = '';
                var discartArr = [];
                var single = true;
                var html = '';
                specAll.forEach(function (d, i) {
                    html += '\n' +
                        '                    <header class="panel-heading" style="background: #ddd">\n' +
                        '                        <b>' + d.name + '</b> <span title="移除" class="remove all" data-index="' + i + '">×</span>\n' +
                        '                    </header>\n' +
                        '                    <div class="row">\n' +
                        '                        <div class="l">\n' +
                        '                            <div class="input-group" >\n' +
                        '                                <input type="text" placeholder="多规格以空格隔开" id="specName' + i + '" class="form-control layui-input specName">\n' +
                        '                                <span class="input-group-addon pointer"><i class="fa fa-plus addChild"></i></span>\n' +
                        '                            </div>\n' +
                        '                        </div>\n' +
                        '                        <div class="r">\n';
                    if (d.value.length > 0) {
                        if (i == 0) {
                            discartArr = d.value
                        } else {
                            discartArr = discarts(discartArr, d.value);
                            single = false;
                        }

                        d.value.forEach(function (d, ii) {
                            html += '<div class="wanl-specs-tag">' + d + '<span title="移除" class="remove"  data-index="' + i + '"  data-index1="' + ii + '">×</span></div>';
                        })
                        thHtml += '<th width="80"> ' + d.name + '</th>';
                    }

                    html += '                        </div>\n' +
                        '                    </div>\n' +
                        '                ';
                })

                $('#specDetail').html(html);

                if (thHtml != '') {
                    var tableHtml = '\n' +
                        '                    <table class="table table-bordered">\n' +
                        '                        <thead>\n' +
                        '                        <tr class="info text-info">\n' + thHtml +
                        '                            <th width="40">图片</th>\n' +
                        '                            <th width="80">原价</th>\n' +
                        '                            <th width="80">现价</th>\n' +
                        '                            <th width="80">库存</th>\n' +
                        //  '                            <th width="80">重量(k)</th>\n' +
                        '                            <th width="80">编码</th>\n' +
                        '                        </tr>\n' +
                        '                        </thead>\n' +
                        '                        <tbody>\n';
                    for (var a = 0; a < discartArr.length; a++) {
                        var tdHtml = '';
                        if (single == true) {
                            tdHtml += '<td>' + discartArr[a] + '</td>';
                        } else {
                            for (var name in discartArr[a]) {
                                tdHtml += '<td>' + discartArr[a][name] + '</td>';
                            }
                        }

                        tableHtml += '<tr>\n' + tdHtml +
                            '                            <td><!---->  <label\n' +
                            '                                    for="skuImg0" class="wanl_sku_img"><input type="hidden" name="specs[img][]" value="' + (specs ? specs[a].img : '') + '" class="imgInput" style="display: none;">\n' +
                            '                                <div class="skuUpload">' + (specs ? ('<img src="' + specs[a].img + '" width="28" height="28">') : '<i class="fa fa-picture-o"></i>') + '</div>\n' +
                            '                            </label></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[original_price][]"  value="' + (specs ? specs[a].original_price : '') + '"\n' +
                            '                                       class="input-sm form-control wanl-market_price layui-input"></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[price][]" value="' + (specs ? specs[a].price : '') + '"\n' +
                            '                                       class="input-sm form-control wanl-price layui-input"></td>\n' +
                            '                            <td><input type="number" data-rule="required" name="specs[stock][]" value="' + (specs ? specs[a].stock : '') + '"\n' +
                            '                                       class="input-sm form-control wanl-stock layui-input"></td>\n' +
                            //'                            <td><input type="number" name="row[weigh][]" class="input-sm form-control wanl-weigh layui-input"></td>\n' +
                            '                            <td><input type="text" name="specs[sku_code][]" value="' + (specs ? specs[a].sku_code : '') + '" class="input-sm form-control wanl-sn layui-input"></td>\n' +
                            '                        </tr>';
                    }

                    tableHtml += '\n' +
                        '                        </tbody>\n' +
                        '                    </table>\n' +
                        '                    <div><span>\n' +
                        //'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t是否要批量设置？\n' +
                        '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t</span></div>\n' +
                        '                ';
                }
                $("[name='specs_all']").val(JSON.stringify(specAll));
                $('#specTable').html(tableHtml);
                uploadBind();
            }

            $(document).on('click', '#addspec', function () {
                var skuJson = $.trim($('#skuJson').val());
                if (skuJson == '') {
                    ea.msg.error('请填写规格');
                    return false;
                }
                skuJsonArr = skuJson.split(' ').filter(function (d) {
                    return d;
                    //console.log(d)
                });

                skuJsonArr.forEach(function (d, i) {
                    specAll.push({
                        name: d,
                        value: []
                    })
                })
                $('#skuJson').val('');
                buildSpec();
                console.log(specAll);
            });
            $(document).on('click', '.addChild', function (d) {
                var index = $('.addChild').index($(this));
                var skuJson = $.trim($('#specName' + index).val());
                if (skuJson == '') {
                    ea.msg.error('请填写规格');
                    return false;
                }
                var skuJsonArr = skuJson.split(' ').filter(function (d) {
                    return d;
                });
                skuJsonArr.forEach(function (d, i) {
                    specAll[index].value.push(d);
                })

                $('#specName' + index).val('');
                buildSpec();
                console.log(specAll);
            })

            form.on('radio(spec_type)', function (data) {
                if (data.value == 0) {
                    $('#specContainer0').show();
                    $('#specContainer1').hide();
                    uploadBind();
                } else {
                    $('#specContainer1').show();
                    $('#specContainer0').hide();
                }
                console.log(data.value);
            });
            uploadBind();

            if (specAll) {
                buildSpec(specs1);
            }
        },
    };
    return Controller;
});